package com.jee.ssm.modules.handheldMachine;

import com.jee.ssm.common.QRCode.ZXingBackGroundUtils;
import com.jee.ssm.common.pay.wxpay.HttpUtil;
import com.jee.ssm.common.pay.wxpay.PayCommonUtil;
import com.jee.ssm.common.pay.wxpay.XMLUtil;
import com.jee.ssm.model.Order;
import com.jee.ssm.model.json.Tip;
import com.jee.ssm.modules.order.services.OrderService;
import org.jdom.JDOMException;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.BufferedReader;
import java.io.IOException;
import java.util.*;

/**
 * 微信生成支付二维码
 */
@Controller
@RequestMapping("/wechatCodePay")
public class WechatPayCode {

    @Resource
    private OrderService orderService;

    /**
     * 生成支付二维码的链接
     * @param request
     * @param response
     * @param orderId　订单的编号
     * totalFee　金额（单位：分）
     * @throws JDOMException
     * @throws IOException
     */
    @RequestMapping("/uniformOrder")
    @ResponseBody
    public Tip uniformOrder(HttpServletRequest request, HttpServletResponse response, String orderId) throws JDOMException, IOException {
        System.out.println("--------------------扫描支付统一下单中-------------------------");
        Order order = orderService.selectById(orderId);
        if(order ==null){
            return  new Tip(2,"暂未获取到订单信息");
        }
        Integer totalFee =(int)(order.getOrderMoney()*100);//正式上线后
//        Integer totalFee = (int) (0.01 *100);//测试
        String nonce_str = UUID.randomUUID().toString().replaceAll("-", "");
        //商户订单号
        //订单生成的机器 IP
        String spbill_create_ip = request.getRemoteAddr(); //获取客户端的真是的IP
        //总金额
        //TODO
        String out_trade_no =orderId+"_"+ (int)(Math.random()*100) ;
        String body ="停车场支付";
        //这里notify_url是 支付完成后微信发给该链接信息，可以判断会员是否支付成功，改变订单状态等。
        SortedMap<Object,Object> packageParams = new TreeMap<Object,Object>();
        packageParams.put("appid", WXSCPayConfig.APPID);
        packageParams.put("mch_id", WXSCPayConfig.MCHID);
        packageParams.put("nonce_str", nonce_str);
        packageParams.put("body", body);
        packageParams.put("out_trade_no", out_trade_no);
        packageParams.put("total_fee", String.valueOf(totalFee));
        packageParams.put("spbill_create_ip", spbill_create_ip);
        packageParams.put("notify_url",WXSCPayConfig.CALLBACK_URL);
        packageParams.put("trade_type", "NATIVE");
        System.out.println("回调路径"+WXSCPayConfig.CALLBACK_URL);
        //请求签名
        String sign = PayCommonUtil.createSign(WXSCPayConfig.CHARACTER, packageParams,WXSCPayConfig.WX_KEY);
        packageParams.put("sign", sign);
        //转换为xml格式的请求串
        String requestXML = PayCommonUtil.getRequestXml(packageParams);
//        //发送请求
        String resXml = HttpUtil.postData(WXSCPayConfig.MCH_URL, requestXML);
//        //返回内容转换为map
        Map map = XMLUtil.doXMLParse(resXml);
        System.out.println(map);
        String resultCode = (String) map.get("return_code");
        String msg = (String) map.get("return_msg");
        if("SUCCESS".equals(resultCode)){
            String codeUrl =(String) map.get("code_url"); //二维码链接
            String baseUrl = request.getSession().getServletContext().getRealPath(""); //获取到项目的真是路径
            String payUrl ="/images/qrcode/wx_"+orderId+".jpg";
            boolean b =ZXingBackGroundUtils.drawLogoQRCode(baseUrl+"/images/icon/wxLogo.jpg",baseUrl+payUrl,codeUrl);
           if(b){
               return  new Tip((Object) payUrl,"微信支付二维码生成成功");
           }else{
               return  new Tip(2,"微信支付二维码生成失败");
           }

        }else{
            return  new Tip(2,msg);
        }
    }


    @RequestMapping(value = "/callback")
    @ResponseBody
    public String callback(HttpServletRequest request) throws IOException {
        System.out.println("===============手持机微信支付回调===============");
        BufferedReader reader = request.getReader();
        String line = "";
        StringBuffer inputString = new StringBuffer();
        String result = null;
        try {
            while ((line = reader.readLine()) != null) {
                inputString.append(line);
            }
            request.getReader().close();
            Map<String, String> restmap = XMLUtil.doXMLParse(inputString.toString());
            if("SUCCESS".equals(restmap.get("result_code"))){
                String out_trade_no = restmap.get("out_trade_no");
                orderService.handleCallBack(out_trade_no,1,request,"wx_");
                result = "<xml><return_code><![CDATA[SUCCESS]]></return_code><return_msg><![CDATA[OK]]></return_msg></xml>";
            }
        } catch(Exception e) {
            e.printStackTrace();
        }
        return result;
    }
}